import { DownOutlined } from '@ant-design/icons'
import { Button, FormInstance, Space } from 'antd'
import React, { FC, memo, ReactNode, useRef, useState } from 'react'
import BaseForm, { IBaseFormComponentRef } from '@/base-ui/base-form'
import { IMyFormProps } from '@/base-ui/base-form/type'
import WithButtonPermission from '@/components/with-button-permission'

interface IProps {
  children?: ReactNode
  config: IMyFormProps
  // 外面可以通过这个属性拿到from实例
  searchClick?: (form: FormInstance | undefined) => void
  resetClick?: (form: FormInstance | undefined) => void
}

const PageSearch: FC<IProps> = (props) => {
  const { config, searchClick, resetClick, children } = props
  const [expand, setExpand] = useState(false)
  const baseForm = useRef<IBaseFormComponentRef>(null)

  function handleSearch() {
    const form = baseForm.current?.getFormInstance()
    searchClick?.(form)
  }

  function handleReset() {
    const form = baseForm.current?.getFormInstance()
    resetClick?.(form)
  }

  return (
    <>
      <BaseForm ref={baseForm} config={config} isSearch isExpand={expand}>
        {children}
      </BaseForm>
      <div style={{ textAlign: 'right', marginRight: '13%' }}>
        <Space size="small">
          <Button size="small" type="primary" onClick={handleSearch}>
            查询
          </Button>
          <Button size="small" onClick={handleReset}>
            重置
          </Button>
          {config?.itemsConfig?.length > 3 && (
            <a
              style={{ fontSize: 12 }}
              onClick={() => {
                setExpand(!expand)
              }}
            >
              <DownOutlined rotate={expand ? 180 : 0} />{' '}
              {expand ? '收起' : '展开'}
            </a>
          )}
        </Space>
      </div>
    </>
  )
}

export default memo(WithButtonPermission(PageSearch))
